﻿
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media;

namespace ConvertImage
{
    /// <summary>
    /// use to get thumbnail from image
    /// </summary>
    public class ThumbnailsHelper : IDisposable
    {
        #region private field
        private int width;
        private int height;
        private string imgPath;
        private bool cutByHeight = true;
        private bool isKeepBlank = true;
        private System.Drawing.Color backgroundColor = System.Drawing.Color.Transparent;
        private bool isKeepSize = true;
        #endregion

        #region constructor
        public ThumbnailsHelper(int width, int height)
        {
            this.width = width;
            this.height = height;
        }

        public ThumbnailsHelper(System.Windows.Size size)
        {
            this.width = (int)size.Width;
            this.height = (int)size.Height;
        }

        public ThumbnailsHelper(string imgPath)
        {
            this.imgPath = imgPath;
        }

        public ThumbnailsHelper()
        { }
        #endregion

        #region public attribute

        public int Width
        {
            get { return width; }
            set { width = value; }
        }

        public int Height
        {
            get { return height; }
            set { height = value; }
        }

        public string ImgPath
        {
            get { return imgPath; }
            set { imgPath = value; }
        }
        public bool CutByHeight
        {
            get { return cutByHeight; }
            set { cutByHeight = value; }
        }

        public bool IsKeepBlank
        {
            get { return isKeepBlank; }
            set { isKeepBlank = value; }
        }

        public System.Drawing.Color BackgroundColor
        {
            get { return backgroundColor; }
            set { backgroundColor = value; }
        }

        public bool IsKeepSize
        {
            get { return isKeepSize; }
            set { isKeepSize = value; }
        }

        #endregion

        #region public methods
        /// <summary>
        /// From Image Path ,to ImageSource
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public System.Windows.Media.ImageSource ConvertFromPath(string path)
        {
            byte[] byteArray = GenerateFromPath(path);
            if (byteArray == null)
                return null;

            if (byteArray.Length == 0)
                return null;

            ImageSourceConverter convert = new ImageSourceConverter();
            try
            {
                return (ImageSource)convert.ConvertFrom(byteArray);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// GenerateFromPath
        /// </summary>
        /// <param name="ms"></param>
        byte[] GenerateFromPath(string path)
        {
            #region prepare
            string filename = Path.GetFileNameWithoutExtension(path);
            string fileExtension = Path.GetExtension(path).ToLowerInvariant();
            if (string.IsNullOrEmpty(fileExtension))
                return null;
            if (!File.Exists(path))
                return null;
            #endregion

            Image oriImg = null;
            try
            {
                //FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                //oriImg = System.Drawing.Image.FromStream(fs, true, false);
                MemoryStream ms = new MemoryStream(File.ReadAllBytes(path));
                oriImg = Image.FromStream(ms);
                //oriImg.GetThumbnailImage()
            }
            catch (Exception ex)
            {
                throw new Exception("original image fail:" + path, ex);
            }

            return GetNewImg(oriImg, fileExtension);
        }

        public void GenerateFromPath(string sourcePath, string aimPath, string extension)
        {
            #region prepare
            string filename = Path.GetFileNameWithoutExtension(sourcePath);
            if (string.IsNullOrEmpty(aimPath))
                return;

            if (string.IsNullOrEmpty(extension))
                return;

            if (!File.Exists(sourcePath))
                return;
            #endregion

            #region get stream
            Image oriImg = null;
            try
            {
                //FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                //oriImg = System.Drawing.Image.FromStream(fs, true, false);
                MemoryStream ms = new MemoryStream(File.ReadAllBytes(sourcePath));
                oriImg = Image.FromStream(ms);
                //oriImg.GetThumbnailImage()
            }
            catch (Exception ex)
            {
                throw new Exception("original image fail:" + sourcePath, ex);
            }
            #endregion

            #region save file
            try
            {
                if (File.Exists(aimPath))
                    File.Delete(aimPath);
                if (!Directory.Exists(Path.GetDirectoryName(aimPath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(aimPath));

                File.WriteAllBytes(aimPath, GetNewImg(oriImg, extension));
            }
            catch (Exception ex)
            {
                throw new Exception("save image fail:" + sourcePath, ex);
            }
            #endregion
        }


        /// <summary>
        /// GenerateFromPath
        /// </summary>
        /// <param name="ms"></param>
        public void GenerateFromPath(string sourcePath, string aimPath)
        {
            string fileExtension = Path.GetExtension(aimPath);
            if (string.IsNullOrEmpty(fileExtension))
                return;
            GenerateFromPath(sourcePath, aimPath, fileExtension);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceStream"></param>
        /// <param name="ms"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public byte[] GenerateFromByte(byte[] source, string fileExtension)
        {
            #region prepare
            if (source == null) return null;
            if (source.Length == 0) return null;
            #endregion

            fileExtension = fileExtension.ToLowerInvariant();
            Image oriImg;
            try
            {
                oriImg = Image.FromStream(new MemoryStream(source));
            }
            catch (Exception ex)
            {
                throw new Exception("convert from stream failure", ex);
            }
            return GetNewImg(oriImg, fileExtension);
        }

        /// <summary>
        ///  new System.Drawing.Image 
        /// </summary>
        /// <param name="oriImg"></param>
        /// <returns></returns>
        private byte[] GetNewImg(Image oriImg, string fileExtension)
        {
            #region   thumb width and height
            Image newImg;

            width = width < 1 ? oriImg.Width : width;
            height = height < 1 ? oriImg.Height : height;

            int ActualWidth = 0;
            int ActualHeight = 0;
            int Srcx = 0;         //left
            int Srcy = 0;         //top


            if (oriImg.Width < oriImg.Height) //by height
            {
                ActualWidth = Height * oriImg.Width / oriImg.Height;
                //Srcx = (width - ActualWidth) / 2;
                ActualHeight = height;
                ActualHeight = ActualHeight < 1 ? 1 : ActualHeight;
                ActualWidth = ActualWidth < 1 ? 1 : ActualWidth;

                newImg = new Bitmap((int)ActualWidth, (int)ActualHeight);
            }
            else
            {
                ActualHeight = width * oriImg.Height / oriImg.Width;
                // Srcy = (height - ActualHeight) / 2;
                ActualWidth = width;
                ActualHeight = ActualHeight < 1 ? 1 : ActualHeight;
                ActualWidth = ActualWidth < 1 ? 1 : ActualWidth;
                newImg = new Bitmap((int)ActualWidth, (int)ActualHeight);
            }

            if (oriImg.Width == width && oriImg.Height == height)
            {
                Srcx = 0;
                Srcy = 0;
                ActualWidth = width;
                ActualHeight = height;
                newImg = new Bitmap((int)width, (int)height);
            }

            #endregion

            #region  draw thumb
            Graphics g = Graphics.FromImage(newImg);
            g.Clear(backgroundColor);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
            g.DrawImage(oriImg, new Rectangle(Srcx, Srcy, ActualWidth, ActualHeight), 0, 0, oriImg.Width, oriImg.Height, GraphicsUnit.Pixel);
            #endregion

            #region  Dispose
            oriImg.Dispose();
            g.Dispose();
            #endregion

            #region save
            MemoryStream ms = new MemoryStream();
            switch (fileExtension)
            {
                case ".jpg":
                    {
                        newImg.Save(ms, ImageFormat.Jpeg); break;
                    }
                case ".png":
                    {
                        newImg.Save(ms, ImageFormat.Png); break;
                    }
                case ".gif":
                    {
                        newImg.Save(ms, ImageFormat.Png); break;
                    }
                case ".bmp":
                    {
                        newImg.Save(ms, ImageFormat.Bmp); break;
                    }
                default:
                    {
                        newImg.Save(ms, ImageFormat.Jpeg); break;
                    }
            }
            #endregion

            newImg.Dispose();
            var imgBytes = ms.ToArray();
            if (imgBytes == null || imgBytes.Length == 0)
            {
                throw new Exception("generate thumb failure");
            }
            return ms.ToArray();
        }
        #endregion

        #region IDisposable

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
